<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    *{
      margin: 0;
      padding: 0;
    }
    .box{
      width: 100px;
      height: 100px;
      background-color: red;
      position: relative;
    }
  
  </style>
</head>
<body>
  <input type="button" value="500">
  <input type="button" value="1000">
  <div class="box"></div>
  <script>
    var btn_500 = document.querySelector('input:nth-child(1)');
    var btn_1000 = document.querySelector('input:nth-child(2)');
    var box = document.querySelector('.box');
    // var current = box.offsetLeft;
    // var target = 500;
    // var step = 10;
    // var timeID = null;
    btn_500.onclick = function(){
      animate(box,box.offsetLeft,500,10);
    }
    btn_1000.onclick = function(){
      animate(box,box.offsetLeft,1000,10);
    }
    // var timeID = null;
    function animate(element,current,target,step){
      if(element.timeID){
        clearInterval(element.timeID);
        element.timeID = null;
      }
      element.timeID = setInterval(function(){
        if(current > target){
          step = -Math.abs(step);
        }
        if(Math.abs(current - target) < Math.abs(step)){
          current = target;
          clearInterval(element.timeID);
        }else{
          current += step;
        }
        element.style.left = current + 'px'
      },30)
    }


  </script>
</body>
</html>